<template>
  <BasicForm @register="registerForm"/>
</template>
<script lang="ts" setup>
import {BasicForm, useForm} from '@apps/antd-admin/src/components/Form/index';
import {formSchema} from '../data/product.data';
import {Api} from '../data/product.api';
import {onMounted} from "vue";
//表单配置
const [registerForm, {setProps, resetFields, setFieldsValue, formSubmit}] = useForm({
  rowKey: 'productId',
  saveApi: Api.save,
  updateApi: Api.update,
  labelWidth: 120,
  schemas: formSchema,
  baseColProps: {
    span: 22,
  },
  showActionButtonGroup: false,
});

async function setData(data) {
  await resetFields();
  if (typeof data.record === 'object') {
    await setFieldsValue({
      ...data.record,
    });
  }
}

// 
onMounted(() => {
  // 监听按键
  let code = ''
  let lastTime, nextTime // 上次时间、最新时间
  let lastCode, nextCode // 上次按键、最新按键
  document.onkeypress = (e) => {
    // 获取按键
    if (window.event) { // IE
      nextCode = e.keyCode
    } else if (e.which) { // Netscape/Firefox/Opera
      nextCode = e.which
    }
    // 如果触发了回车事件(扫码结束时间)
    if (nextCode === 13) {
      if (code.length < 3) return // 手动输入的时间不会让code的长度大于2，所以这里只会对扫码枪有
      finCode(code) // 获取到扫码枪输入的内容，做别的操作
      code = ''
      lastCode = ''
      lastTime = ''
      return
    }
    nextTime = new Date().getTime() // 记录最新时间
    if (!lastTime && !lastCode) { // 如果上次时间和上次按键为空
      code += e.key // 执行叠加操作
    }
    // 如果有上次时间及上次按键
    if (lastCode && lastTime && nextTime - lastTime > 30) { // 当扫码前有keypress事件时,防止首字缺失
      code = e.key
    } else if (lastCode && lastTime) {
      code += e.key
    }
    lastCode = nextCode
    lastTime = nextTime
  }
})

function finCode(code) {
  if (code) {
    if (code.length == 10) {
      let info = {nfc: code};
      setFieldsValue(info);
    } else {
      let info = {productSku: code};
      setFieldsValue(info);
    }
  }
}

/**
 * 提交事件
 */
async function handleSubmit(options) {
  await formSubmit(options);
}

/**
 * 暴露给父组件调用的方法
 */
defineExpose({
  setData,
  handleSubmit,
});
</script>
